package com.binguo.service;

import com.binguo.common.enums.CodeType;
import com.binguo.common.exception.ServiceException;
import com.binguo.model.model.PhoneVerification;
import com.binguo.model.repository.PhoneVerificationRepository;
import com.binguo.common.sms.JavaSmsApi;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import tk.mybatis.mapper.entity.Condition;

import java.util.Date;
import java.util.Optional;
import java.util.Random;

import static com.binguo.common.exception.ErrorCode.CODE_ERROR;
import static com.binguo.common.exception.ErrorCode.PHONE_NOT_EXIST;

/**
 * Created by haibang on 18/5/7.
 */
@Service
public class SMSservice {

    @Autowired
    PhoneVerificationRepository phoneVerificationRepository;

    public void sendInitCode(String phone, CodeType codeType){
        String code = _createCode();

        _saveOrUpdatePhoneverification(phone, codeType, code);

        JavaSmsApi.sendVerify(phone, code);
    }

    //fixme haibang 是否要限制单日短信次数?
    public void checkInitCode(String phone, String code, CodeType codeType){
        Optional<PhoneVerification> phoneVerificationOptional = findOne(phone, codeType);
        if(phoneVerificationOptional.isPresent()){
            PhoneVerification phoneVerification = phoneVerificationOptional.get();
            if(!code.equals(phoneVerification.getCode())) throw new ServiceException(CODE_ERROR);
        }else throw new ServiceException(PHONE_NOT_EXIST);

    }


    private void _saveOrUpdatePhoneverification(String phone, CodeType codeType, String code){
        Optional<PhoneVerification> phoneVerificationOptional = findOne(phone, codeType);
        if(phoneVerificationOptional.isPresent()){
            PhoneVerification phoneVerification = phoneVerificationOptional.get();
            phoneVerification.setCode(code);
            phoneVerification.setUpdated(new Date());
            phoneVerificationRepository.update(phoneVerification);
        } else {
            PhoneVerification phoneverification = PhoneVerification.builder()
                    .phone(phone)
                    .code(code)
                    .type(codeType.getCode().byteValue())
                    .triedtimes(1).build();
            phoneVerificationRepository.save(phoneverification);
        }
    }




    private Optional<PhoneVerification> findOne(String phone, CodeType codeType){
        Condition condition = new Condition(PhoneVerification.class);
        condition.or().andEqualTo("phone", phone)
                .andEqualTo("type", codeType.getCode());
        return phoneVerificationRepository.findByCondition(condition).stream().findFirst();
    }




    private String _createCode(){
        return new Random().nextInt(899999) + 100000 + "";
    }


}
